#!/bin/sh
#
# Copyright (C) 2000-2025 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Show the broken media bug(s) again. Test by Graham Keeling.
#
# This test will wait forever whilst the last job waits for an appendable
# volume.
# You can run ./bin/bconsole -c bin/bconsole.conf from within the regress
# directory, and use 'list media' to see where the volumes have ended up, as
# well as any other commands you like.
#
# The problem(s):
# - Write two jobs to two different volumes.
# - Purge them manually. The two volumes end up in the Scratch pool.
# - Start a large job. It takes a volume from the Scratch pool, places it
#   in its own pool and starts writing to it.
# - While the first job is still running, start a second job.
# - A sort of chaos then follows.
#   The second job sees that there are no JobMedia records associated with the 
#   first volume (which is in a separate pool), and purges it, moving it
#   through Scratch and into its own pool. It then decides not to use that
#   volume and hangs around 'waiting for an appendable Volume' - even though
#   there is the other purged volume sitting untouched in the Scratch pool.
#   Meanwhile, the first job finishes and sets the volume status of its volume
#   (that is now in the wrong pool) to 'Used'.

TestName="broken-media-bug-2-test"
. scripts/functions

cwd=`pwd`
scripts/cleanup
/bin/cp -f scripts/broken-media-bug-2-bacula-dir.conf bin/bacula-dir.conf
/bin/cp -f scripts/broken-media-bug-2-bacula-sd.conf bin/bacula-sd.conf
/bin/cp -f scripts/test-bacula-fd.conf bin/bacula-fd.conf
/bin/cp -f scripts/test-console.conf bin/bconsole.conf
hugefile=${cwd}/build/hugefile
hugefilesize=300
echo "${cwd}/build" >${cwd}/tmp/file-list

start_test

#echo "Creating huge ${hugefilesize}M file..."
dd if=/dev/urandom of="$hugefile" bs=1M count="$hugefilesize" >/dev/null 2>&1
#echo "Done"

cat >tmp/bconcmds <<END_OF_DATA
@$out /dev/null
messages
@$out tmp/log1.out
setdebug level=150  storage=File
setdebug level=150  Director
label storage=File volume=TestVolume0001 pool=Scratch
label storage=File volume=TestVolume0002 pool=Scratch
list media
llist media
run job=Second yes
wait
run job=Second yes
wait
list media
llist media
purge volume
3
1
purge volume
3
2
list media
llist media
messages
run job=First yes
messages
quit
END_OF_DATA

run_bacula

# Give the first job a bit of time to get going.
sleep 5

cat >tmp/bconcmds <<END_OF_DATA
setdebug level=150  storage=File
setdebug level=150  Director
list media
llist media
messages
@$out tmp/log2.out
run job=Second yes
wait
messages
restore fileset=Set1 where=${cwd}/tmp/bacula-restores select all storage=File done
yes
wait
list media
llist media
messages
quit
END_OF_DATA

run_bconsole
check_for_zombie_jobs storage=File
stop_bacula

check_two_logs
check_restore_diff
rm -f "$hugefile"
end_test
